package com.probiz.estore.system.dao.impl;

import java.util.ArrayList;
import java.util.List;

import com.probiz.estore.common.model.system.Region;
import com.probiz.estore.common.model.system.TaxRate;
import com.probiz.estore.common.model.system.TaxRate.FilterHqlName;
import com.probiz.estore.core.dao.impl.HibernateGenericDaoImpl;
import com.probiz.estore.system.dao.RegionDao;
import com.probiz.estore.system.dao.TaxRateDao;


/**
 * TaxRate Data Access Object (DAO) implementation.
 * Developer introduced interfaces should be declared here. Won't get overwritten.
*/
public class TaxRateDaoImpl extends HibernateGenericDaoImpl<TaxRate> implements TaxRateDao {
	private RegionDao regionDao;
	
	public void setRegionDao(RegionDao regionDao) {
		this.regionDao = regionDao;
	}

	@Override
	protected void initFilterHqlMap() {
		filterHqlMap.put(FilterHqlName.COUNT_EXIST, "from TaxRate t where t.tax.taxId=? and t.productType.productTypeId=? and t.region.regionId=?");
		filterHqlMap.put(FilterHqlName.COUNT_EXIST_EXCLUDE_SELF, "from TaxRate t where t.tax.taxId=? and t.productType.productTypeId=? and t.region.regionId=? and t.taxRateId!=?");
		
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.system.dao.TaxRateDao#getRevenueTax(java.lang.Integer)
	 */
	public List<TaxRate> getRevenueTax(Integer productTypeId) {
		return this.findByHql("from TaxRate t where t.productType.productTypeId="+productTypeId);
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.system.dao.TaxRateDao#getTaxRateListByRegionIdAndProductTypeId(java.lang.Integer, java.lang.Integer)
	 */
	public List<TaxRate> getTaxRateListByRegionIdAndProductTypeId(Integer regionId, Integer productTypeId){
		Region region = regionDao.getById(regionId);
		if(null == region){
			return new ArrayList<TaxRate>();
		}else{
			StringBuffer sql=new StringBuffer("from TaxRate t");
			StringBuffer sb=new StringBuffer();
			List<Integer> regionIds=new ArrayList<Integer>();
			regionIds.add(region.getRegionId());
			Region parentRegion  = region.getParent();
			while(parentRegion != null){
				regionIds.add(parentRegion.getRegionId());
				parentRegion  = parentRegion.getParent();
			}
			for (Integer id : regionIds) {
				sb.append(",").append(id);
			}
			sb.setCharAt(0, '(');
			sb.append(')');
			sql.append(" where t.productType.productTypeId="+productTypeId);
			for(Integer id: regionIds){
				sql.append(" and (t.region.regionId in ").append(sb).append(" or t.region.regionId in (select ri.region.regionId from RegionItem ri where ri.item.regionId in ").append(sb).append("))");
			}
			
			return findByHql(sql.toString());
		}
		
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.system.dao.TaxRateDao#countAll()
	 */
	public Long countAll(){
		return this.countByHql("from TaxRate");
	}
}